<template>
  <div class="component-slider">
    <div class="box">
      <transition name="slide">
        <img :src="activeSlide" :key="activeSlide">
      </transition>
    </div>
    <div class="indicator" v-if="!simplified">
      <template v-for="(it, index) in list">
        <i :key="index" :class="{active: index === activeIndex}" @click="activeIndex = index"></i>
      </template>
    </div>
  </div>
</template>
<script>
export default {
  name: 'r-slider',
  props: {
    speed: {
      type: Number,
      default: 5000
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      activeIndex: 0,
      timerId: null
    }
  },
  computed: {
    size () {
      return this.list.length
    },
    simplified () {
      return this.size === 1
    },
    activeSlide () {
      return this.list[this.activeIndex]
    }
  },
  mounted () {
    if (!this.simplified) {
      this.timerId = setInterval(this.next, this.speed)
    }
  },
  beforeDestroy () {
    if (!this.simplified && this.timerId) {
      clearInterval(this.timerId)
    }
  },
  methods: {
    next () {
      this.activeIndex = this.projection(this.activeIndex + 1)
    },
    // 投影回数组，正常范围 >= 0, < size
    projection (index) {
      const {size} = this
      return index < 0 ? index + size : (index >= size ? index % size : index)
    }
  }
}
</script>
<style lang="scss">
  @import "../styles/index";

  .component-slider {
    position: relative;

    .box {
      @extend %flex-start;
      overflow: hidden;
    }

    img {
      display: block;
      width: 100%;
    }

    .slide-enter-active,
    .slide-leave-active {
      transition: transform 0.8s ease-in-out;
    }

    .slide-enter-to,
    .slide-leave-to {
      transform: translateX(-100%);
    }

    .indicator {
      position: absolute;
      width: 100%;
      bottom: 10px;
      @extend %flex-center;

      i {
        display: block;
        width: 8px;
        height: 8px;
        margin: 0 5px;
        border-radius: 50%;

        &:not(.active) {
          border: 1px solid $color-line-default;
          background-color: white;
        }

        &.active {
          background-color: $color-warning;
          border: 1px solid $color-warning;
        }
      }
    }
  }
</style>
